<template>
<el-container>
    <el-header>
      <TopBar />
  </el-header>
  <el-main class="el-main">
    <div class="content">
      <!-- 加载状态 -->
      <div v-if="loading" class="loading-container">
        <el-loading :fullscreen="false" text="加载中..."></el-loading>
      </div>

      <!-- 没有社团的提示 -->
      <div v-else-if="clubinfo.length === 0" class="no-clubs-container">
        <el-empty description="您还没有加入任何社团" :image-size="200">
          <!-- <el-button type="primary" @click="$router.push('/club/discover')">去发现社团</el-button> -->
        </el-empty>
      </div>

      <template v-else>
        <!-- 社团列表 -->
        <div class="myclub-list">
          <el-card
            v-for="club in clubinfo"
            :key="club.id"
            class="card-club"
            :class="{ 'selected': selectedClub?.id === club.id }"
            @click="selectClub(club)"
          >
            <div class="img-container">
              <img
                :src="club.clubimg ? `http://localhost:5000/uploads/${club.clubimg}` : '../assets/shehui.png'"
                alt=""
                class="myclubimg round-img"
              >
            </div>
            <div class="clubname">{{club.clubname}}</div>
          </el-card>
        </div>

        <!-- 社团名片 -->
        <div class="club-details" v-if="selectedClub.id">
          <div class="img-details">
            <img
              :src="selectedClub.clubimg  ? `http://localhost:5000/uploads/${selectedClub.clubimg}` : '../assets/shehui.png'"
              alt=""
              class="clubimg-details round-img"
            >
          </div>
          <div class="clubname-details">{{ selectedClub.clubname }}</div>
          <!-- 进入社团主页 -->
          <el-button class="enter-club" type="primary" round @click="goToClubPage(selectedClub.id)">进入社团主页</el-button>
          <!-- 社团活动展示 -->
          <div class="activities">
            <div v-if="loadingDetails" class="loading-activities">
              <el-icon class="is-loading"><loading /></el-icon>
            </div>
            <div v-else-if="sortedActivities.length === 0" class="no-activities">没有活动</div>
            <template v-else>
              <el-card
                v-for="(activity, index) in sortedActivities"
                :key="activity.activeid"
                class="activity-card"
                :style="{ zIndex: sortedActivities.length - index }"
              >
                <div v-if="index === 0 && sortedActivities.length >= 2" class="activity-count">
                  {{ sortedActivities.length }}
                </div>
                <h4>{{ activity.activename }}</h4>
                <div class="activity-info">
                  <p><i class="el-icon-time"></i> {{ activity.activetime }}</p>
                  <p><i class="el-icon-location"></i> {{ activity.activeadd }}</p>
                </div>
              </el-card>
            </template>
          </div>
        </div>

        <!-- 社团帖子 -->
        <div class="myclubpost" v-if="selectedClub.id">
          <div v-if="loadingDetails" class="loading-posts">
            <el-skeleton :rows="5" animated />
          </div>
          <div v-else-if="selectedClub.posts.length === 0" class="no-posts">
            <el-empty description="暂无帖子" :image-size="100"></el-empty>
          </div>
          <div v-else class="post-waterfall-wrapper">
            <PostWaterfall
              ref="postWaterfall"
              :posts="selectedClub.posts"
              :columns="0"
              @post-click="openPostDetail"
            />
          </div>
        </div>
      </template>
    </div>
    <PostDetailModal v-if="selectedPost" :post="selectedPost" @close="selectedPost = null" />
  </el-main>
</el-container>
</template>

<script setup>
import TopBar from '../components/TopBar.vue'
import PostDetailModal from '../components/PostDetailModal.vue'
import PostWaterfall from '../components/PostWaterfall.vue'
import { ref, computed, onMounted, nextTick, watch } from 'vue'
import { useRouter } from 'vue-router'
import axios from 'axios' // 导入axios
import { Loading } from '@element-plus/icons-vue' // 导入Loading图标
import { ElMessage } from 'element-plus'; // 新增导入

const router = useRouter()
const selectedPost = ref(null);
const postWaterfall = ref(null);
const loading = ref(false); // 主加载状态
const loadingDetails = ref(false); // 社团详情加载状态
const defaultTouxiang = '/src/assets/touxiang.png'
const openPostDetail = (post) => {
  selectedPost.value = post;
}

// 替换静态数据为API获取的数据
const clubinfo = ref([]);

// 默认选中第一个社团，初始为空对象
const selectedClub = ref({
  id: null,
  clubname: '',
  clubimg: '',
  posts: [],
  active: []
});

// 加载社团数据
const loadClubs = async () => {
  loading.value = true; // 显示加载中状态
  try {
    // 从服务器获取用户加入的社团列表
    const token = localStorage.getItem('token'); // 获取存储的token
    const response = await axios.get('http://localhost:5000/users/me/clubs', {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    });

    // 处理返回的数据
    const clubs = response.data.map(club => ({
      id: club._id,
      clubname: club.clubname,
      clubimg: club.clubimg || '../assets/sehhui.png', // 设置默认图片
      description: club.description,
      posts: [], // 先设为空数组，后续可以添加获取帖子的逻辑
      active: [] // 先设为空数组，后续可以添加获取活动的逻辑
    }));

    clubinfo.value = clubs;

    // 如果有社团数据，选中第一个
    if (clubs.length > 0) {
      selectClub(clubs[0]);
      // 加载所选社团的帖子和活动
      await loadClubDetails(clubs[0].id);
    }
  } catch (error) {
    console.error('加载社团数据失败', error);
    if (error.response) {
      console.error('错误详情:', error.response.data);
    }
  } finally {
    loading.value = false; // 隐藏加载中状态
  }
};

// 加载特定社团的详细信息（帖子和活动）
const loadClubDetails = async (clubId) => {
  if (!clubId) return;

  loadingDetails.value = true; // 开始加载详情
  try {
    // 获取社团帖子
    const token = localStorage.getItem('token');
    const postsResponse = await axios.get(`http://localhost:5000/clubs/${clubId}/posts`, {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    });

    // 获取社团活动
    const activitiesResponse = await axios.get(`http://localhost:5000/clubs/${clubId}/activities`, {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    });

    // 处理帖子数据
    const posts = postsResponse.data.map(post => {
      // 确保 post.likedBy 是一个数组
      const likedByArray = Array.isArray(post.likedBy) ? post.likedBy : [];
      // 假设后端已经返回了 isLiked 字段，如果没有，需要获取当前用户ID来判断
      const isLiked = post.isLiked !== undefined ? post.isLiked : false; // 优先使用后端返回的 isLiked
      console.log(post.authorimg)
      return {
// 使用展开运算符保留所有原始字段，包括 _id
        ...post,
        // 如果其他地方确实需要 id 字段，可以额外添加
        id: post._id,
        likes: likedByArray.length || 0,
        liked: isLiked, // 使用处理后的 liked 状态
        authorimg: post.authorimg || defaultTouxiang, // 处理头像
        // 可以在这里进一步处理评论数据，例如头像URL，但建议在后端或Modal组件内处理
        comments: post.comments || [],
        // id: post._id,
        title: post.title,
        description: post.content || post.description || '', // 兼容 content 和 description
        image: post.image, // 构造图片 URL
        author: post.author || '匿名用户',
        // authorimg: post.authorimg, // 构造作者头像 URL
        // likes: likedByArray.length || 0,
        // liked: isLiked, // 使用处理后的 liked 状态
        // comments: post.comments || [] // 评论数据可能也需要处理头像URL，在后端处理更佳
      };
    });

    // 处理活动数据
    const activities = activitiesResponse.data.map(activity => ({
      activeid: activity._id,
      activename: activity.activename,
      activetime: new Date(activity.activetime).toLocaleDateString('zh-CN'),
      activeadd: activity.activeadd,
      description: activity.description,
      status: activity.status,
      // 如果活动有海报，也需要处理 URL
      poster: activity.poster ? `http://localhost:5000/uploads/${activity.poster}` : null
    }));

    // 更新社团数据
    const selectedClubIndex = clubinfo.value.findIndex(c => c.id === clubId);
    if (selectedClubIndex !== -1) {
      clubinfo.value[selectedClubIndex].posts = posts;
      clubinfo.value[selectedClubIndex].active = activities;

      // 如果当前选中的是这个社团，也更新selectedClub
      if (selectedClub.value.id === clubId) {
        selectedClub.value.posts = posts;
        selectedClub.value.active = activities;
      }
    }
  } catch (error) {
    console.error('加载社团详情失败', error);
    if (error.response) {
      console.error('错误详情:', error.response.data);
    }
  } finally {
    loadingDetails.value = false; // 结束加载详情
  }
};

// 处理社团选择
const selectClub = async (club) => {
  selectedClub.value = club;
  // 选择社团时加载该社团的详细信息
  await loadClubDetails(club.id);
}

const goToClubPage = (clubId) => {
  router.push(`/club/${clubId}`)
}

// 计算排序后的活动
const sortedActivities = computed(() => {
  if (!selectedClub.value || !selectedClub.value.active) return [];
  return [...selectedClub.value.active].sort((a, b) => new Date(a.activetime) - new Date(b.activetime));
});

// 监听社团变化，重新计算瀑布流布局
watch(() => selectedClub.value, () => {
  nextTick(() => {
    if (postWaterfall.value) {
      setTimeout(() => {
        postWaterfall.value.calculateColumns();
        postWaterfall.value.resizeAllWaterfallItems();
      }, 100);
    }
  });
});

// 在组件挂载后，确保瀑布流正确初始化并加载数据
onMounted(() => {
  const token = localStorage.getItem('token'); // 新增检查
  if (!token) { // 新增检查
    ElMessage.warning('请先登录'); // 新增
    router.push('/login'); // 新增
    return; // 新增
  }

  // 加载社团数据
  loadClubs();

  nextTick(() => {
    if (postWaterfall.value) {
      setTimeout(() => {
        postWaterfall.value.calculateColumns();
        postWaterfall.value.resizeAllWaterfallItems();
      }, 200);
    }
  });
});
</script>

<style>
body {
  background-color: #1f1b24;
  margin: 0;
  padding: 0;
}
</style>
<style scoped>
::-webkit-scrollbar{
  display: none;
}
::-webkit-sticky{
  display: block;
}

.content {
  position: absolute; /* 绝对定位 */
  top: 60px; /* 距离顶部的距离等于顶部区域的高度 */
  left: 10vw; /* 距离左侧的距离等于左侧区域的宽度 */
  right: 10vw;
  bottom: 0; /* 距离底部为0，撑满剩余空间 */
  padding: 20px; /* 为内容添加内边距 */
  overflow-y: auto;

}
.myclub-list {
  position: fixed;
  top: 80px; /* 调整顶部距离，留出顶栏空间 */
  width: 15vw;
  padding: 10px;
  height: 87vh;
  background-color: #28232e;
  border-radius: 15px;
  overflow: auto;
  z-index: 100;
}
.club-details {
  margin-left: 17vw; /* 300px + 20px margin */
  margin-right: 10px;
  float: left;
  width: 61vw;
  height: 400px;
  padding-right: 10px;
  background-color: #28232e;
  color: aliceblue;
  border-radius: 15px;
  position: relative;
}

.clubname{
  text-align: center;
  margin-top: 8px;
  font-size: 20px;
}
.myclubimg {
  width: 7vw;
  height: 7vw;
}
.clubimg-details {
  width:250px;
  height:250px;
}
.img-container {
    display: flex;
    justify-content: center; /* 水平居中 */
}
.img-details{

    display: flex;
    justify-content: center; /* 水平居中 */
}
.round-img {

    border-radius: 50%; /* 圆形效果 */
    object-fit: cover; /* 保持图像比例 */
}
.card-club {
  width: 14.8vw;
  height: 12vw;
  margin-bottom: 10px;
  background-color: #1f1b24;
  border-radius: 10px;
  border: 1px solid transparent;
  border-color: #505050;
  color: aliceblue;
}
.pagination {
  float: right;
}
/* 我的社团帖子容器 */
.myclubpost {
  margin-left: 17vw; /* 与 club-details 对齐 */
  width: 60.5vw;
  background-color: #28232e;
  float: left;
  margin-top: 20px;
  padding: 10px;
  border-radius: 15px;
}

.post-waterfall-wrapper {
  width: 100%;
}

.custom-card {
  border: 1px solid transparent;
  border-radius: 15px;
  transition: all 0.2s ease;
  float: left;
  width: 260px;
  margin-left: 10px;
  margin-top: 10px;
  background-color: #1f1b24;
}
.custom-card .card-title {
  color:aliceblue; /* 设置文字颜色 */
  text-decoration: none;
  font-weight: 670;
  max-height: 50px;
  overflow: hidden; /* 隐藏溢出的内容 */
}
.custom-card:hover .card-title {
  color: #00aeff; /* 设置悬停时文字颜色 */
}
.el-card:hover {
  transform: scale(1.02); /* 悬停时缩放效果 */
  box-shadow: 5px 5px 10px rgba(0, 0, 0, 0.2); /* 添加阴影效果 */
}
.card-image {
  width: 100%;
  height: 200px;
  object-fit: cover;
  /* max-height: 200px; */
  border-radius: 12px;
}
/* 进入按钮居中 */
.enter-club {
  display: block; /* 设置为块级元素 */
  margin: 20px auto; /* 上下边距20px，左右自动居中 */
  width: fit-content; /* 宽度适应内容 */
  font-weight: bold;
}
/* 帖子作者信息 */
.author-wrapper {
  align-items: center;
  color:aliceblue;
  display: flex;
  font-size: 13px;
  height: 20px;
  justify-content: space-between;
  margin-top: 6px;
}
.touxiang {
  width: 16px;
  height: 16px;
}
.like-wapper {
  align-items: center;
  cursor: pointer;
  display: flex;
  position: relative;
}

/* 添加选中状态样式 */
.card-club.selected {
  border: 2px solid #00aeff;
  background-color: #00aeff54;
}

.clubname-details {
  text-align: center; /* 居中对齐 */
  margin: 0 20px; /* 添加左右边距 */
  font-size: 24px;
  font-weight: bold;
}

.img-details {
  margin: 20px; /* 添加外边距 */
}

.activities {
  position: absolute;
  top: 20px;
  right: 20px;
  width: 300px;
  perspective: 1000px;

  &:hover {
    .activity-count {
      opacity: 0;
      transform: scale(0);
    }

    .activity-card {
      transform: translateY(0) rotateX(0) !important;
      opacity: 1;
      margin-top: 16px;
    }
  }
}

.no-activities {
  color: #666;
  text-align: center;
  padding: 20px;
  background: #1f1b24;
  border-radius: 8px;
  border: 1px solid #333;
}

.activity-card {
  margin-top: 0;
  background: linear-gradient(135deg, #2c3e50, #3498db);
  color: white;
  border-radius: 12px;
  position: relative;
  transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
  border: none;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  padding: 16px;
  backdrop-filter: blur(5px);

  &:not(:first-child) {
    margin-top: -140px;
    transform: translateY(0) rotateX(45deg);
    opacity: 0.6;
  }

  h4 {
    margin: 0 0 12px 0;
    font-size: 18px;
    font-weight: 600;
    color: #fff;
  }
}

.activity-info {
  p {
    margin: 8px 0;
    display: flex;
    align-items: center;
    font-size: 14px;
    color: rgba(255, 255, 255, 0.9);

    i {
      margin-right: 8px;
      font-size: 16px;
    }
  }
}

.activity-count {
  position: absolute;
  top: -6px;
  right: -6px;
  background: rgba(255, 255, 255, 0.2);
  color: white;
  min-width: 20px;
  height: 20px;
  border-radius: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  font-weight: 500;
  backdrop-filter: blur(4px);
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
  z-index: 2;
  padding: 0 5px;
  border: 1px solid rgba(255, 255, 255, 0.3);
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);

  &::before {
    content: '';
    position: absolute;
    top: -1px;
    right: -1px;
    bottom: -1px;
    left: -1px;
    background: linear-gradient(45deg, rgba(255, 255, 255, 0.2), rgba(255, 255, 255, 0.1));
    border-radius: 11px;
    z-index: -1;
    opacity: 0.3;
    animation: gentle-pulse 3s infinite;
  }
}

@keyframes gentle-pulse {
  0% {
    opacity: 0.3;
  }
  50% {
    opacity: 0.15;
  }
  100% {
    opacity: 0.3;
  }
}

/* 添加加载状态样式 */
.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 80vh;
  width: 100%;
}

/* 添加空社团状态样式 */
.no-clubs-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 80vh;
  width: 100%;
  color: #b0bec5;
}

/* 添加空帖子状态样式 */
.no-posts {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 40px 0;
  color: #b0bec5;
}

/* 添加加载帖子状态样式 */
.loading-posts {
  padding: 20px;
}

/* 添加加载活动状态样式 */
.loading-activities {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100px;
  color: #409EFF;
  font-size: 24px;
}

/* 添加卡片的渐变边框效果 */
.activity-card::before {
  content: '';
  position: absolute;
  top: -1px;
  left: -1px;
  right: -1px;
  bottom: -1px;
  background: linear-gradient(45deg, #00aeff, #3498db);
  border-radius: 13px;
  z-index: -1;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.activity-card:hover::before {
  opacity: 1;
}

@media (max-width: 1000px) {
  .activities {
    display: none;
  }
}
</style>
